﻿#include "citycodeutils.h"

#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QDebug>

CityCodeUtils::CityCodeUtils()
{

}

QString CityCodeUtils::getCodeFromName(QString cityName)
{
    if(cityMap.isEmpty()){
        initCityMap();
    }
    QMap<QString, QString >::iterator cityCode = cityMap.find(cityName);
    if(cityCode == cityMap.end()){
        return "";
    }
    return cityCode.value();



}

void CityCodeUtils::initCityMap()
{
    QFile file(":/local/local.json");
    file.open(QIODevice::ReadOnly);
    QByteArray rawData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(jsonDoc.isArray()){
        QJsonArray citys = jsonDoc.array();
        for(QJsonValue val : citys){
            if(val.isObject()){
                QString cityName = val["cityName"].toString();
                QString cityCode = val["cityCode"].toString();
                cityMap.insert(cityName,cityCode);
            }
        }
    }
}
